# -*- coding: UTF-8 -*-
import re
import time

from datetime import datetime
from selenium import webdriver
from selenium.common.exceptions import TimeoutException, NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from config import config
from pyquery import PyQuery as pq

from raw.write_to_excel import write_info, delete_file


def is_not_finished(is_hot_update, count):
    if is_hot_update and (count > 3):
        return False
    else:
        try:
            WebDriverWait(driver, 10).until(
                EC.visibility_of_element_located((By.XPATH, "//a[contains(text(),'See older')]")))
            return True
        except TimeoutException:
            return False


def loadNext():
    driver.find_element_by_xpath("//a[contains(text(),'See older')]").click()
    time.sleep(1)


def not_empty(s):
    return s and s.strip()


def handling(blogname):
    # print( driver.find_element_by_xpath("//a[@target='_blank']") .text
    # write_count(count, config.COUNT_TXT)

    html = driver.page_source
    if html:
        doc = pq(html)
        resultList = []
        _last_kickoff = '2000-11-11'
        items = doc('.feed-pick-title')
        print(u'分析:', len(items))
        for item in items.items():
            try:
                item_view = item.find('.col-xs-12.no-padding')

                plain_item_view_txt = re.sub(r'\r\n|\n|\r/gm', ";", item_view.text())

                if item_view.find('h3').find('.combo-toggle') or plain_item_view_txt.find(
                        'Combo') != -1:
                    pick_type = 'Combo'
                    match = 'Combo'
                    sport = 'Combo'
                    category = ''
                    kickoff = _last_kickoff
                    kickoff_time = '00:00'
                else:
                    match = item_view.find('h3').find('a').text()
                    if not match:
                        match = list(filter(not_empty, plain_item_view_txt.split(';')))[0]
                    pick_type = 'LIVE' if item_view.find('.labels').find('.label.label-danger') else 'Single'
                    sport_line = re.sub(r'\r\n|\n|\r/gm', "",
                                        item_view.find('.sport-line').text().replace('Kick off:', ''))
                    sport_line_splits = sport_line.split('/')
                    sport = sport_line_splits[0]
                    category = sport_line_splits[1]
                    strptime = datetime.strptime(not_empty(sport_line_splits[2]), '%d %b %Y, %H:%M')
                    kickoff = strptime.strftime('%Y-%m-%d')
                    kickoff_time = strptime.strftime('%H:%M')
                    _last_kickoff = kickoff

                pick_txt = item_view.find('.pick-line').text()
                pick = pick_txt.split('@')[0]
                odd = float(pick_txt.split('@')[1])
                stake = int(item_view.find('.labels').find('.label.label-default').text().replace('/10', ''))
                win = item_view.find('.labels').find('.enable-tooltip.text-green')
                lost = item_view.find('.labels').find('.enable-tooltip.text-danger')
                try:
                    profit = float(win.text() if win else lost.text())
                except ValueError:
                    profit = 0
                result = win.attr('data-original-title') if win else lost.attr('data-original-title')

                resultList.append((
                    not_empty(match), not_empty(pick), odd, stake, pick_type, profit,
                    not_empty(result), not_empty(sport), not_empty(category), not_empty(kickoff), kickoff_time))

            except IndexError:
                print('index errr')
            except ValueError:
                print('value err')
        write_info(blogname, resultList)

    else:
        print(u'抓取网页失败，跳过')


def fetchBlog(blogname, is_hot_update):
    time.sleep(2)
    driver.get(config.get_search_link(blogname))
    try:
        driver.find_element_by_xpath('//button[@id="impliedsubmit"]').click()
    except NoSuchElementException:
        print("")
    time.sleep(2)
    driver.find_element_by_xpath('//a[@class="btn btn-default btn-blogmenu"]').click()
    WebDriverWait(driver, 20).until(
        EC.visibility_of_element_located((By.XPATH, '//a[@data-value="picks"]')))
    driver.find_element_by_xpath('//a[@data-value="picks"]').click()

    WebDriverWait(driver, 20).until(
        EC.visibility_of_element_located((By.XPATH, '//div[@id="_blogInnerContent"]')))
    # wait = ui.WebDriverWait(driver, 10)
    # wait.until(lambda driver: driver.find_element_by_xpath('//tr[@class="tr-filter"]'))

    try:
        driver.find_element_by_xpath('//span[@data-original-title="Tipster offers paid service"]')
        driver.find_element_by_class_name('tr-filter').click()
        time.sleep(2)
    except NoSuchElementException:
        print("")

    hot_update_page_count = 0
    if not is_hot_update:
        delete_file(config.get_excel_name_s(blogname, 'a'))

    while is_not_finished(is_hot_update, hot_update_page_count):
        loadNext()
        hot_update_page_count += 1
    handling(blogname)
    print(blogname + '          , ok!')


def fetch(blog_array, is_hot_update):
    for item in blog_array:
        fetchBlog(item, is_hot_update)


# tsuu vladdow lucky-7
driver = webdriver.Chrome()
